package main

import (
	"context"
	"flag"
	"fmt"
	"github.com/gorilla/mux"
	"go-kit/demo10/utils"
	pd2 "go-kit/go-client/pd"
	"google.golang.org/grpc"
	"log"
	netHttp "net/http"
	"os"
	"os/signal"
	"strconv"
	"syscall"
)

//挂起一个HTTP 服务 并把请求 传递给service 层
func main() {

	name := flag.String("name", "", "服务注册名称")

	port := flag.Int("port", 0, "端口号")

	flag.Parse()

	if *name == "" {
		fmt.Println("你他妈的给我输入服务名称")
	}

	if *port < 1 {
		fmt.Println("瞎逼啊你 不输入端口号")
	}

	utils.SetServiceNameAndPort(*name, *port)

	r := mux.NewRouter()

	cnon, err := grpc.Dial(":7999", grpc.WithInsecure())

	if err != nil {
		log.Fatal(err)
	}

	defer cnon.Close()

	prodClient := pd2.NewProServiceClient(cnon)

	//GET 方式访问
	r.Methods("GET").Path(`/user/{uid:\d+}`).HandlerFunc(func(writer netHttp.ResponseWriter, request *netHttp.Request) {
		res, err := prodClient.GetProStock(context.Background(), &pd2.ProRequest{ProductId: 24})

		if err != nil {
			log.Fatal(err)

		}

		fmt.Println(res.ProductStock)
		writer.Header().Set("Content-type", "application/json")

		res = fmt.Sprintf(`{"status":"%v"}`, res)

		writer.Write([]byte())
	})

	r.Methods("GET").Path(`/health`).HandlerFunc(func(writer netHttp.ResponseWriter, request *netHttp.Request) {

		writer.Header().Set("Content-type", "application/json")
		writer.Write([]byte(`{"status":"OK"}`))

	})

	errChan := make(chan error)

	go func() {
		//调用注册服务
		utils.RegService()

		err := netHttp.ListenAndServe(":"+strconv.Itoa(utils.ServicePort), r)

		if err != nil {
			fmt.Println(err)
			errChan <- err
		}
	}()

	go func() {
		sigChan := make(chan os.Signal)

		signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)

		errChan <- fmt.Errorf("%s", <-sigChan)

	}()

	getErr := <-errChan

	utils.UnRegService()

	fmt.Println(getErr)

}
